package org.hxzon.tapestry5.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.tapestry5.Field;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.ValidationException;
import org.apache.tapestry5.ioc.MessageFormatter;
import org.apache.tapestry5.services.FormSupport;
import org.apache.tapestry5.validator.AbstractValidator;

public class NumberString extends AbstractValidator<Void, String> {
    private static final Pattern NumberStringPattern = Pattern.compile("\\d*");

    public NumberString() {
        super(null, String.class, "numberString");
    }

    public void validate(Field field, Void constraintValue, MessageFormatter formatter, String value) throws ValidationException {
        Matcher matcher = NumberStringPattern.matcher(value);
        if (!matcher.matches()) {
            throw new ValidationException(buildMessage(formatter, field));
        }
    }

    private String buildMessage(MessageFormatter formatter, Field field) {
        return formatter.format(field.getLabel());
    }

    public void render(Field field, Void constraintValue, MessageFormatter formatter, MarkupWriter writer, FormSupport formSupport) {
        formSupport.addValidation(field, "numberString", buildMessage(formatter, field), null);
    }

}
